package classifiers;

import draw.ExploringMedics;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.util.LinkedList;

/**
 * paint region in red color
 */
public class SimpleDrawRegion extends AbstractDoAction implements IsRepaint {

    BufferedImage rootImage = null;
    int mask[][];
    final int INCOMP = 23423;
    final int UNEXPL = 6547;
    int minx = Integer.MAX_VALUE;
    int miny = Integer.MAX_VALUE;
    int maxx = 0;
    int maxy = 0;

    public SimpleDrawRegion(int[][] regionsOfInterest, BufferedImage rootImage) {
        super(regionsOfInterest);
        this.rootImage = rootImage;
        initMask();
    }

    @Override
    public void doAction(int xStart, int yStart) {
        WritableRaster rast = rootImage.getRaster();
        int paintIn[] = {255, 0, 0, 255};
        reInitBounds();
        findComponent(xStart, yStart);

        for (int i = minx; i <= maxx; i++) {
            for (int j = miny; j < maxy; j++) {
                if (mask[i][j] == INCOMP) {
                    int sample[] = new int[4];
                    rast.getPixel(i, j, sample);
                    for (int k = 0; k < 4; k++) {
                        sample[k] = (sample[k] + paintIn[k] / 2);
                    }
//                    rast.setPixel(i, j, sample);
                    rast.setPixel(i, j, paintIn);
                    mask[i][j] = UNEXPL;
                }

            }
        }
    }

    @Override
    public BufferedImage getImage() {
        return rootImage;
    }

    void initMask() {
        mask = new int[width][height];
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                mask[i][j] = UNEXPL;
            }
        }
    }

    void reInitBounds() {
        minx = Integer.MAX_VALUE;
        miny = Integer.MAX_VALUE;
        maxx = 0;
        maxy = 0;
    }

    void findComponent(int xStart, int yStart) {
        LinkedList<Integer> xQueue = new LinkedList<Integer>();
        LinkedList<Integer> yQueue = new LinkedList<Integer>();

        xQueue.push(xStart);
        yQueue.push(yStart);

        int dx[] = {-1, 1, 0, 0};
        int dy[] = {0, 0, -1, 1};

        while (!xQueue.isEmpty()) {
            int x = xQueue.pop();
            int y = yQueue.pop();

            if (x >= width || y >= height || x < 0 || y < 0) {
                continue;
            }

            if (mask[x][y] == UNEXPL && regionsOfInterest[x][y] == ExploringMedics.WHITE) {
                mask[x][y] = INCOMP;

                minx = x < minx ? x : minx;
                miny = y < miny ? y : miny;
                maxx = x > maxx ? x : maxx;
                maxy = y > maxy ? y : maxy;

                for (int i = 0; i < 4; i++) {
                    xQueue.push(x + dx[i]);
                    yQueue.push(y + dy[i]);
                }
            }
        }
    }
}
